package com.woniuxy.service.Impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.demo.Result;
import com.woniuxy.dto.UserRelatedDto.UserTableDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    //MVC自带的JSON序列化工具对象
    private ObjectMapper om = new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        UserTableDetails utd = (UserTableDetails) authentication.getPrincipal();
        utd.setUserPassword(null);
        //设置json响应
        httpServletResponse.setCharacterEncoding("utf8");
        httpServletResponse.setContentType("application/json;charset=utf8");
        //构建Result
        Result result = Result.newInstance()
                .setCode(200).setMsg("登录成功").setData(utd);
        //把result序列化成JSON字符串
        String json = om.writeValueAsString(result);
        //响应
        httpServletResponse.getWriter().write(json);
        httpServletResponse.getWriter().flush();
    }
}
